import os
import time

"""
批压缩指定路径的文件/文件夹.
压缩指定路径下的所有文件，文件夹，分别独立保存到指定目录.
"""
# 指定压缩文件夹路径.
source_dir = 'C:\\Users\\GaoMing\\Desktop\\0000\\'



# 备份保存到
save_dir = 'C:\\Users\\GaoMing\\Desktop\\0000\\'

# 排除的指定文件夹
# ignore_folder = ['.vscode', 'node_modules', '.git', '.svn']
ignore_folder = []

# 排除的任意指定文件
# ignore_files = ['*.log', '*.md', '*.tmp' ,'*.html']
ignore_files = []

# 排除指定路径下的文件(会保留相应路径下的文件夹)
# ignore_path_files = ['app/*', 'log/*', 'runtime/session/*']
ignore_path_files = []

ignore_str = ''
for i in ignore_files:
    ignore_str = ignore_str+'-x!'+i+' '

for i in ignore_folder:
    ignore_str = ignore_str+'-xr!*'+i+' '

for i in ignore_path_files:
    ignore_str = ignore_str+'-x!'+i+' '

#  ==================== 将文件压缩 ===============
# 获取需要压缩的项目文件夹
dirs = os.listdir(source_dir)
# dirs=["demo1","demo1"] # 或者自定义项目名

# 指定不压缩的文件夹
skip_dirs = ['更新说明', '历史备份', '杂项']

for source_d in dirs:   
    # 限定是否压缩.
    if source_d in skip_dirs:
        continue
    new_d = ''
    if os.path.isdir(source_dir+source_d):
        new_d = source_d
        print('*'*30,'{}当前路径是文件夹'.format(new_d),'*'*30)
    else:
        d_list = source_d.split('.')
        for i in range(len(d_list) - 1):
            new_d = new_d + d_list[i]
        
    save_file = save_dir+new_d+'.7z'
    source_dir_ = source_dir + source_d
    # 拼接命令（按需要自行修改)
    #这里有一个问题，就是在python环境下密码是'gaozhi'，而不是gaozhi，但是不加引号运行报错，在powershell运行密码是gaozhi.
    # cmd = "7z a -t7z -m0=lzma2 -mx=9 -mfb=64 -md=32m -ms=on -mhe=on -p'gaozhi' {} {} {}".format(save_file, source_dir_, ignore_str)

    # 我的建议是不带密码压缩，除非是在是有需求.
    cmd = "7z a -t7z -m0=lzma2 -mx=9 -mfb=64 -md=32m -ms=on -mhe=on {} {} {}".format(save_file, source_dir_, ignore_str)

    # 执行压缩
    os.system(cmd)
    print(source_dir_, '=====>', save_file)
